package com.cloud.message.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cloud.common.bean.PageInfo;
import com.cloud.message.dao.ConsumerDao;
import com.cloud.message.dto.ConsumerQueryParamDTO;
import com.cloud.message.entity.Consumer;
import com.cloud.message.service.ConsumerService;
import com.cloud.message.service.MessagePendingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;

@Service
public class ConsumerServiceImpl extends ServiceImpl<ConsumerDao, Consumer> implements ConsumerService {

    @Autowired
    private MessagePendingService messagePendingService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeById(Serializable id) {
        Consumer consumer = getById(id);
        messagePendingService.removePending(consumer.getServiceName(), consumer.getTopic());
        return super.removeById(id);
    }

    @Override
    public boolean exist(String topic, String serviceName) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq(Consumer.TOPIC, topic);
        wrapper.eq(Consumer.SERVICE_NAME, serviceName);
        if (list(wrapper).size() > 0) {
            return true;
        }
        return false;
    }

    @Override
    public PageInfo<Consumer> getPage(ConsumerQueryParamDTO consumerQueryDTO) {
        QueryWrapper<Consumer> wrapper = new QueryWrapper();
        IPage page = page(new Page(consumerQueryDTO.getPageNo(), consumerQueryDTO.getPageSize()), wrapper);
        return new PageInfo(page);
    }
}
